import DatePicker from "components/antd-compatible/date-picker";
import React, {Component} from 'react';
import { Button, Checkbox, Divider, Form, Icon, Input, Select, Switch,  Popover, message } from 'antd';
import {messages} from 'share/common';
import PDService from 'containers/enterprise-manage/person-manage/person-detail/person-detail.service';
import moment from 'moment';
import {connect} from 'react-redux';
const FormItem = Form.Item;
const Option = Select.Option;

const firstNameRule = [
  {
    required: true,
    message: messages('common.please.input')/*请输入*/
  },
  {
    max: 30,
    message: messages('basic-5.key249')/*不能超过30个字符*/
  },
];

class NewIdCard extends Component {

  state = {
    loading: false,
    card: {},//当前编辑或新增的银行卡
    cardTypeList: [],//银行卡类型的数组
    nationalityList: [],//国籍
    genderData: [],
    disableCountry: false,
  };

  componentDidMount() {
    const {card, cardTypeList, nationalityList} = this.props.params;

    this.setState({card, cardTypeList, nationalityList});
    this.getSystemValueList(1007)
      .then(res => {
        this.setState({
          genderData: res.data.values
        })
      });
  }

  //去添加卡
  addCard = (e) => {
    const { isForceFillOut } = this.props.params;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let card = Object.assign(this.state.card, {
          firstName: values.firstName,
          lastName: values.lastName,
          cardNo: values.cardNo,
          gender: values.gender,
          birthday: values.birthday ? values.birthday.format() : null,
          cardExpiredTime: values.cardExpiredTime ? values.cardExpiredTime.format() : null
        });
        if (!card.gender && isForceFillOut) {
          let str = messages('basic-5.key283')/*性别*/;
          message.error(messages('basic-5.key399',{arg1: str})/*请填写{arg1}*/)
          return
        } else if (!card.birthday && isForceFillOut) {
          let str = messages('basic-5.key282')/*生日*/;
          message.error(messages('basic-5.key399',{arg1: str})/*请填写{arg1}*/)
          return
        } else if (!card.cardExpiredTime && isForceFillOut) {
          let str = messages('basic-5.key400')/*证件到期时间*/;
          message.error(messages('basic-5.key399',{arg1: str})/*请填写{arg1}*/)
          return
        }
        this.createUpdateCard(card);
      }
    });
  };
  createUpdateCard = (card) => {
    this.setState({
      loading: true,
    });
    if (card.contactCardOID) {
      PDService.updateContactCard(card)
        .then((res) => {
          this.setState({
            loading: false,
          });
          this.props.close();
        })
        .catch((err) => {
          this.setState({
            loading: false,
          });
        });
    } else {
      PDService.creatContactCard(card)
        .then((res) => {
          this.setState({
            loading: false,
          });
          this.props.close();
        })
        .catch((err) => {
          this.setState({
            loading: false,
          });
        });
    }
  };
  //状态
  switchCardStatusChange = (e) => {
    let { card } = this.state;
    card.enable = e;
    this.setState({
      loading: false,
      card
    });
  };
  //默认
  handleCardDefaultChange = (e) => {
    let { card } = this.state;
    card.default = e.target.checked;
    this.setState({
      loading: false,
      card
    });
  };
  handleNationalityChange = (e) => {
    //国籍
    let { card } = this.state;
    card.nationalityCode = e;
    this.setState({
      loading: false,
      card
    });
  };
  //渲染国籍选项
  renderNationalityOption = (data) => {
    if (data && data.length) {
      return data.map((item) => {
        return <Option value={item.value} key={item.value}>{item.messageKey}</Option>;
      });
    } else {
      return (null);
    }
  };
  //证件类型
  handleCardTypeChange = (e) => {
    let { card } = this.state, type = e + "", code = "";
    card.cardType = type;
    switch (type) {
      case '103': code = 'TW';break;
      case '104': code = 'HK';break;
      case '106': code = '';break;
      default: code = 'CN';
    }
    card.nationalityCode = code;
    this.props.form.setFields({nationality: {value: code}})
      this.setState({
        card
      });
  };
  //渲染证件类型
  renderCardTypeOption = (data) => {
    if (data && data.length) {
      return data.map((item) => <Option value={item.value}
                                        key={item.code}>{item.messageKey}</Option>);
    } else {
      return (null);
    }
  };

  disabledBirDate= (current) => {
    return moment(current).isAfter(moment(new Date()), 'day');
  };

  //不能小于于startDate
  disabledEndDate = (current) => {
    return moment(current).isBefore(moment(new Date()), 'day');
  }

  cancelCard = () => {
    this.props.form.resetFields();
    this.props.close();
  };

  //渲染性别
  renderGenderOption = (data) => {
    if (data && data.length) {
      return data.map((item) => {
        return <Option value={item.value} key={item.value}>{item.messageKey}</Option>
      })
    } else {
      return (<Option value={1} key={1}>
        {messages('basic-5.key272')/*女*/}
      </Option>)
    }
  };

  render() {
    const { loading, nationalityList, cardTypeList, genderData, disableCountry } = this.state;
    const { card, isForceFillOut } = this.props.params;
    const { getFieldDecorator } = this.props.form;
    let nameTips = (
      <div>
        <p>{messages('basic-5.key401')/*1.中文姓名填写*/}</p>
        <p>{messages('basic-5.key402')/*可直接在姓字段填写完整姓名。若证件不为身份证或国籍不为“中国大陆”，姓和名必须用英文字母填写，并确保与乘机所持证件一致。*/}</p>
        <p>{messages('basic-5.key403')/*2.英文姓名填写*/}</p>
        <p>{messages('basic-5.key404')/*若持护照乘机，必须按照护照显示区分姓与名，middle name填写在名栏中，不区分大小写。如joe jerad/potter，在姓处输入potter，在名处输入joe jerad。*/}</p>
        <p>{messages('basic-5.key405')/*3. 姓名中有特殊符号“.”“-”等*/}</p>
        <p>{messages('basic-5.key406')/*在姓栏中, 可不用输入；在名中用空格代替。例如：“jame.M-C./Black.S-A ”，在姓中输入BlackSA ，在名中输入为“jame M C”。*/}</p>
      </div>
    );
    const formItemLayout = {
      labelCol: {span: 8},
      wrapperCol: {span: 16}
    },
      cardState = this.state.card, disabled = !cardState.cardType,
      available=['102', '106', '104',].indexOf(cardState.cardType + '') === -1,
      HongMacao = [
      {
        allChoice: null,
        code: "HK",
        common: true,
        corporationOIDs: null,
        createdDate: "2018-04-16T08:47:38Z",
        customEnumerationItemOID: "90c46636-6461-4a11-827d-833d674c34e8",
        customEnumerationName: null,
        customEnumerationOID: "71f073df-b32a-469c-a390-3e19d2daaeed",
        departmentDTOs: null,
        departmentOIDs: null,
        enabled: true,
        grantType: "USER",
        i18n: null,
        id: "1000000004449478",
        keyword: null,
        lastModifiedDate: "2018-07-02T13:25:50Z",
        messageKey: "中国香港",
        patientia: false,
        remark: null,
        returnChoiceUserOIDs: null,
        sequenceNumber: "999",
        systeminit: true,
        title: null,
        userGroupIds: null,
        userOIDs: null,
        userSummaryDTOs: null,
        value: "HK",
      },
      {
        allChoice: null,
        code: "MO",
        common: true,
        corporationOIDs: null,
        createdDate: "2018-04-16T08:47:38Z",
        customEnumerationItemOID: "98c550f3-d4c8-4fe0-89f1-2194ea4fed1f",
        customEnumerationName: null,
        customEnumerationOID: "71f073df-b32a-469c-a390-3e19d2daaeed",
        departmentDTOs: null,
        departmentOIDs: null,
        enabled: true,
        grantType: "USER",
        i18n: null,
        id: "1000000004449480",
        keyword: null,
        lastModifiedDate: "2018-07-02T13:25:57Z",
        messageKey: "中国澳门",
        patientia: false,
        remark: null,
        returnChoiceUserOIDs: null,
        sequenceNumber: "999",
        systeminit: true,
        title: null,
        userGroupIds: null,
        userOIDs: null,
        userSummaryDTOs: null,
        value: "MO",
      }
    ];
    let currentMenu = this.props.currentMenuPermission.currentMenu || {};
    return (
      <div>
        <Form onSubmit={this.addCard} onChange={this.handleFormChange} className={'new-form'}>
          {/*状态*/}
          <FormItem {...formItemLayout}
                    label={messages('common.column.status')/*状态*/}
                    colon={true}>
            {getFieldDecorator('enable', {
              initialValue: card.enable
            })(
              <Switch
                checked={card.enable}
                checkedChildren={<Icon type="check"/>}
                unCheckedChildren={<Icon type="cross"/>}
                onChange={this.switchCardStatusChange}/>
            )}
          </FormItem>

          {/*是否默认*/}
          <FormItem {...formItemLayout}
                    label={messages('basic-5.key388')/*设为默认*/}
          >
            {getFieldDecorator('default', {
              initialValue: card.default
            })(
              <Checkbox
                checked={card.default}
                onChange={this.handleCardDefaultChange}
              >
                {messages('basic-5.key389')/* 是（只能有一个默认)*/}
              </Checkbox>
            )}
          </FormItem>
          <div className="standard-divider-title">{messages('basic-5.key176')/*基础信息*/}</div>
          <FormItem {...formItemLayout}
                    label={messages('basic-5.key407')/*证件类型*/}
          >
            {getFieldDecorator('cardType', {
              initialValue: card.cardTypeName,
              rules: [
                {
                  required: true,
                  message: messages('common.please.input')/*请输入*/
                },
              ],
            })(
              <Select
                className="select-cardType"
                showSearch
                placeholder={messages('common.select')/*请选择*/}
                onChange={this.handleCardTypeChange}
                filterOption={(input, option) => option.props.children.toLowerCase()
                  .indexOf(input.toLowerCase()) >= 0}
              >
                {this.renderCardTypeOption(cardTypeList)}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('basic-5.key408')/*证件号*/}
          >
            {getFieldDecorator('cardNo', {
              initialValue: card.originalCardNo,
              rules: [
                {
                  required: true,
                  message: messages('common.please.input')/*请输入*/
                },
                {
                  max: 30,
                  message: messages('basic-5.key249')/*不能超过30个字符*/
                },
              ],
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/} disabled={disabled}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={card.cardType == '101' || card.cardType == '107' ? messages('basic-5.key95')/*姓名*/ : messages('basic-5.key409')/*姓*/}
          >
            {getFieldDecorator('lastName', {
              initialValue: card.lastName,
              rules: firstNameRule,
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/} disabled={disabled}/>
            )}
          </FormItem>
          {/*如果是英文名这个才必须填写*/}
          {!(card.cardType == '101' || card.cardType == '107') &&
            <FormItem {...formItemLayout} label={messages('basic-5.key410')/*名*/}>
            {getFieldDecorator('firstName', {
              initialValue: card.firstName,
              rules: firstNameRule
            })(
              <Input placeholder={messages('common.please.input')/*请输入*/} disabled={disabled}/>
            )}
            </FormItem>
          }
          <FormItem {...formItemLayout}
                    label={messages('basic-5.key282')/*生日*/}
                    colon={true}>
            {getFieldDecorator('birthday', {
              initialValue: card.birthday ? moment(card.birthday) : undefined,
              rules: [{
                required: currentMenu.key !== "person-manage",
                message: messages('basic-5.key2')/*请选择temp*/
              }],
            })(
              <DatePicker
                style={{width: "66%"}}
                format={'YYYY-MM-DD'}
                disabledDate={this.disabledBirDate}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('basic-5.key283')/*性别*/}
                    colon={true}>
            {getFieldDecorator('gender', {
              initialValue: card.gender,
              rules: [{
                required: currentMenu.key !== "person-manage",
                message: messages('basic-5.key2')/*请选择temp*/
              }],
            })(
              <Select
                className="select-country"
                showSearch
                placeholder={messages('common.select')/*请选择*/}
                optionFilterProp="children"
                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              >
                {this.renderGenderOption(genderData)}
              </Select>
            )}
          </FormItem>

          <FormItem {...formItemLayout}
                    label={messages('basic-5.key411')/*国籍*/}
          >
            {getFieldDecorator('nationality', {
              initialValue: card.nationality,
              rules: [{
                required: currentMenu.key !== "person-manage",
                message: messages('basic-5.key2')/*请选择temp*/
              }],
            })(
              <Select
                className="select-nationality"
                showSearch
                disabled={available || disabled}
                placeholder={messages('common.select')/*请选择*/}
                onChange={this.handleNationalityChange}
                filterOption={(input, option) => option.props.children.toLowerCase()
                  .indexOf(input.toLowerCase()) >= 0}
              >
                {
                  this.renderNationalityOption(cardState.cardType + '' === '104' ? HongMacao : nationalityList)
                }
              </Select>
            )}
          </FormItem>

          <FormItem {...formItemLayout}
                    label={messages('basic-5.key400')/*证件到期时间*/}
          >
            {getFieldDecorator('cardExpiredTime', {
              initialValue: card.cardExpiredTime ? moment(card.cardExpiredTime) : undefined,
              rules: [{
                required: currentMenu.key !== "person-manage",
                message: messages('basic-5.key2')/*请选择temp*/
              }],
            })(
              <DatePicker
                disabled={disabled}
                style={{width: "66%"}}
                format={'YYYY-MM-DD'}
                disabledDate={this.disabledEndDate}/>
            )}
          </FormItem>

          <div className="footer-operate" style={{backgroundColor: '#ffffff', left: '0px'}}>
            <Button type="primary" onClick={this.addCard} loading={loading}>
              {messages('common.save')/*保存*/}
            </Button>
            &nbsp;&nbsp;&nbsp;
            <Button onClick={this.cancelCard}>
              {messages('common.cancel')/*取消*/}
            </Button>
          </div>

        </Form>
      </div>
    );
  }

}

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
  }
}
const WrappedNewIdCard = Form.create()(NewIdCard);
export default connect(mapStateToProps)(WrappedNewIdCard);
